import re
from python_baway.common.xcommon import xshow_list, sep

xfile = open('x_sub.html', 'r')
xtext = xfile.read()
xfile.close()

xregexp = re.compile(r'<h(\d+)>(.*?)</h\1>', re.IGNORECASE | re.DOTALL)

sep('sub by lambda')
xresult = xregexp.sub((lambda m: f'HEAD #{m.group(1)} {m.group(2)}'), xtext)
print(xresult)

sep('sub by string')
xresult2 = xregexp.sub(r'HEAD #\1 \g<2>', xtext)
print(xresult2 == xresult)

sep('my sub procedure by search')
xmatches = []
xpos = 0
while True:
    xmatch = xregexp.search(xtext, xpos)
    if xmatch is None:
        break
    print(xmatch)
    xmatches.append(xmatch)
    xpos = xmatch.end()
xmatches = xmatches[::-1]
xshow_list(xmatches)

xresult3 = xtext
for xmatch in xmatches:
    xprefix = xresult3[:xmatch.start()]
    xsuffix = xresult3[xmatch.end():]
    xinfix = f'HEAD #{xmatch.group(1)} {xmatch.group(2)}'
    xresult3 = xprefix + xinfix + xsuffix
print(xresult3 == xresult)



